//
//  RequestManger.m
//  MyPorject
//
//  Created by Yuki on 2021/1/26.
//

#import "RequestManger.h"
@interface RequestManger ()
/**  请求类  **/
@property (nonatomic , strong)AFHTTPSessionManager  *manager;
@end

static RequestManger *_instance;


///请求地址
NS_INLINE NSString *BaseRequestURlStr(){
#ifdef DEBUG
    return @"https://apix.jhaotian.com/";
#else
    return @"https://apix.jhaotian.com/";
#endif
}

///获取Token
NS_INLINE NSString *GetToken(){
    return  @"";
}

@implementation RequestManger

///初始化单例
+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:NULL]init];
        ///设置类
        [_instance _setupManager];
    });
    return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    return [self shareInstance];
}
- (id)copy{
    return [RequestManger shareInstance];
}
- (id)mutableCopy{
    return [RequestManger shareInstance];
}
- (id)copyWithZone:(NSZone *)zone{
    return [RequestManger shareInstance];
}

#pragma mark - --------- 设置类  ---------
- (void)_setupManager{
    self.manager = [AFHTTPSessionManager manager];
    self.manager.requestSerializer.timeoutInterval = 30.0f;///超时时间
    self.manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];///安全策略
    self.manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;///缓存策略
    self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    AFHTTPResponseSerializer *response = [AFHTTPResponseSerializer serializer];
    [response setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",@"text/html", nil]];
    self.manager.responseSerializer = response;
}

///公共参数
- (NSDictionary *)publicParam{
    NSDictionary *publicParam = @{
        @"system":@"iOS",
        @"version":[[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"],///当前版本
        @"telType":PhoneSystem()///手机型号
    };
    return publicParam;
}

///post请求 请求不放在body中
- (void)postRequestWithCmdStr:(NSString *)cmdStr
                    withParam:(NSDictionary *)param
                 successBlock:(void(^)(NSDictionary *respDic))successBlock
                failuredBlock:(void(^)(NSString *errorStr))failuredBlock{
    if (cmdStr.isEmptyStr){
        if (failuredBlock) {
            failuredBlock(@"请求地址不能为空");
        }
        return;
    }
    
    ///需要额外添加请求协议：
    [self.manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    NSString *urlStr = [BaseRequestURlStr() stringByAppendingString:cmdStr];///请求地址
    
    [self.manager POST:urlStr parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            ///请求成功
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (successBlock) {
                successBlock(dic);
            }
        }else{
            ///请求失败
            [task cancel];
            if (failuredBlock) {
                failuredBlock(@"请求出现失败");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [task cancel];///取消任务
        NSString *errorStr = @"";
        if ([FormatStr(error.userInfo[@"NSLocalizedDescription"]) isEqualToString:@"似乎已断开与互联网的连接。"]) {
            errorStr = @"网络异常，请检查网络是否连接";
        }else{
            errorStr = error.userInfo[@"NSLocalizedDescription"];
        }
        if (failuredBlock) {
            failuredBlock(errorStr);
        }
    }];
    
}

///post请求 请求放在body中
- (void)postRequest_bodyWithCmdStr:(NSString *)cmdStr
                         withParam:(NSDictionary *)param
                      successBlock:(void (^)(NSDictionary *respDic))successBlock
                     failuredBlock:(void (^)(NSString *errorStr))failuredBlock{
    if (cmdStr.isEmptyStr) {
        if (failuredBlock) {
            failuredBlock(@"请求地址不能为空");
        }
        return;
    }
    NSString *urlStr = [BaseRequestURlStr() stringByAppendingString:cmdStr];
    
    /** data为参数转data类型 **/
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:nil error:nil];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSString *token = GetToken();
    if (!token.isEmptyStr) {
        [request addValue:token forHTTPHeaderField:@"Chyu-Auth"];
    }
    
    NSData *body = [[NSData alloc] init];
    if (param != nil) {
        body  = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
    }
    
    [request setHTTPBody:body];
    [[self.manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            if (responseObject) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                if (successBlock) {
                    successBlock(dic);
                }
            }else{
                if (failuredBlock) {
                    failuredBlock(@"请求出现失败");
                }
            }
        }else{
            NSString *errorStr = @"";
            if ([FormatStr(error.userInfo[@"NSLocalizedDescription"]) isEqualToString:@"似乎已断开与互联网的连接。"]) {
                errorStr = @"网络异常，请检查网络是否连接";
            }else{
                errorStr = error.userInfo[@"NSLocalizedDescription"];
            }
            if (failuredBlock) {
                failuredBlock(errorStr);
            }
        }
    }]resume] ;
    
}


///上传图片
- (void)postUploadImgWithCmdStr:(NSString *)cmdStr
                      withImage:(UIImage *)img
                   successBlock:(void (^)(NSDictionary *respDic))successBlock
                  failuredBlock:(void (^)(NSString *errorStr))failuredBlock{
    if (cmdStr.isEmptyStr) {
        if (failuredBlock) {
            failuredBlock(@"请求地址不能为空");
        }
        return;
    }
    NSString *urlStr = [BaseRequestURlStr() stringByAppendingString:cmdStr];
    
    /** data为参数转data类型 **/
    ///需要额外添加请求协议：
    [self.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSData *body = [[NSData alloc] init];
    if (img != nil) {
        body  = UIImageJPEGRepresentation(img, 1);
    }
    
    [self.manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:body name:@"file" fileName:@"avatar.jpg" mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            ///请求成功
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (successBlock) {
                successBlock(dic);
            }
        }else{
            ///请求失败
            [task cancel];
            if (failuredBlock) {
                failuredBlock(@"请求出现失败");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [task cancel];///取消任务
        NSString *errorStr = @"";
        if ([FormatStr(error.userInfo[@"NSLocalizedDescription"]) isEqualToString:@"似乎已断开与互联网的连接。"]) {
            errorStr = @"网络异常，请检查网络是否连接";
        }else{
            errorStr = error.userInfo[@"NSLocalizedDescription"];
        }
        if (failuredBlock) {
            failuredBlock(errorStr);
        }
    }];
    
}


///get请求
- (void)getRequestWithCmdStr:(NSString *)cmdStr
                   withParam:(NSDictionary *)param
                successBlock:(void(^)(NSDictionary *respDic))successBlock
               failuredBlock:(void(^)(NSString *errorStr))failuredBlock{
    if (cmdStr.isEmptyStr){
        if (failuredBlock) {
            failuredBlock(@"请求地址不能为空");
        }
        return;
    }
    NSString *urlStr = [BaseRequestURlStr() stringByAppendingString:cmdStr];
    if (!GetToken().isEmptyStr) {
        [self.manager.requestSerializer setValue:GetToken() forHTTPHeaderField:@"Chyu-Auth"];
    }
    [self.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [self.manager GET:urlStr parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            ///请求成功
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (successBlock) {
                successBlock(dic);
            }
        }else{
            ///请求失败
            [task cancel];
            if (failuredBlock) {
                failuredBlock(@"请求出现失败");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [task cancel];///取消任务
        NSString *errorStr = @"";
        if ([FormatStr(error.userInfo[@"NSLocalizedDescription"]) isEqualToString:@"似乎已断开与互联网的连接。"]) {
            errorStr = @"网络异常，请检查网络是否连接";
        }else{
            errorStr = error.userInfo[@"NSLocalizedDescription"];
        }
        if (failuredBlock) {
            failuredBlock(errorStr);
        }
    }];
    
}



///请求URL
- (void)getURLRequestWithCmdStr:(NSString *)cmdStr
                      withParam:(NSDictionary *)param
                   successBlock:(void(^)(NSDictionary *respDic))successBlock
                  failuredBlock:(void(^)(NSString *errorStr))failuredBlock{
    if (cmdStr.isEmptyStr){
        if (failuredBlock) {
            failuredBlock(@"请求地址不能为空");
        }
        return;
    }
    
    ///需要额外添加请求协议：
    [self.manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [self.manager GET:cmdStr parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            ///请求成功
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (successBlock) {
                successBlock(dic);
            }
        }else{
            ///请求失败
            [task cancel];
            if (failuredBlock) {
                failuredBlock(@"请求出现失败");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [task cancel];///取消任务
        NSString *errorStr = @"";
        if ([FormatStr(error.userInfo[@"NSLocalizedDescription"]) isEqualToString:@"似乎已断开与互联网的连接。"]) {
            errorStr = @"网络异常，请检查网络是否连接";
        }else{
            errorStr = error.userInfo[@"NSLocalizedDescription"];
        }
        if (failuredBlock) {
            failuredBlock(errorStr);
        }
    }];
    
}

@end
